package com.chixing.util;

import com.chixing.config.QiniuConfig;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.io.File;
import java.util.UUID;

public class UploadImgUtil {

    private static final String ACCESS_KEY = QiniuConfig.getAccessKey();
    private static final String SECRET_KEY = QiniuConfig.getSecretKey();
    private static final String BUCKET_NAME = QiniuConfig.getBucket();

    private static Auth auth = Auth.create(ACCESS_KEY,SECRET_KEY);

    private static Configuration cfg = new Configuration(Region.region2());
    //...其他参数参考类注释
    private static  UploadManager uploadManager = new UploadManager(cfg);


    //重命名文件名
    private static String newName(String oldName){
        String[] datas = oldName.split("\\.");
       String type =  datas[datas.length-1];
        String temp = UUID.randomUUID().toString().replace("-","") ;
        String newName = temp+"." + type;
        System.out.println(newName);
       return newName;

    }

    //上传到bucket
    private static String getUploadToken(){
        String token= auth.uploadToken(BUCKET_NAME);
        return token;
    }

    /**
     * 开始上传文件
     * @param file 文件对象
     * @param fileName 文件原始名
     * @return  返回上传后 图片在七牛云服务器的URL地址
     */
    public static String upload(byte[] file, String fileName){
        String url = null;
        Response response = null;
        String imgName = null;

        try {
            response =uploadManager.put(file,newName(fileName),getUploadToken());
            imgName = (String) response.jsonToMap().get("key");
        } catch (QiniuException e) {
            e.printStackTrace();
        }

//        url = QiniuConfig.getDomainOfBucket()+imgName;
        url = QiniuConfig.getDomainOfBucket();
        System.out.println("文件上传到服务器，在七牛云中的url :" + url);

        return imgName;
    }


    /**
     * 开始上传文件
     * @param file 文件对象
     * @param fileName 文件原始名
     * @return  返回上传后 图片在七牛云服务器的URL地址
     */
    public static String upload(File file, String fileName){
        String url = null;
        Response response = null;
        String imgName = null;

        try {
            response = uploadManager.put(file,newName(fileName),getUploadToken());
            imgName = (String) response.jsonToMap().get("key");
        } catch (QiniuException e) {
            e.printStackTrace();
        }

//        url = QiniuConfig.getDomainOfBucket()+imgName;
        url = QiniuConfig.getDomainOfBucket();
        System.out.println("文件上传到服务器，在七牛云中的url :" + url);

        return url;
    }

}
